package com.owen.he.jee.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * H5跨域支持Interceptor
 * @author owen.he
 */
public class AccessControlInterceptor implements HandlerInterceptor {
	private static final Logger logger = LoggerFactory.getLogger(AccessControlInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		final String uri = request.getRequestURI();
		final String origin = request.getHeader(HttpHeaders.ORIGIN);
		if (isValid(origin)) {
			response.setHeader("Access-Control-Allow-Origin", origin);
			response.setHeader("Access-Control-Allow-Credentials", "true");
			response.setHeader("Access-Control-Allow-Headers", "Content-Type, accept, apikey, sign, timestamp");
			response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
			logger.info("request uri:{}, origin:{}, access success", uri, origin);
			return !"options".equalsIgnoreCase(request.getMethod());
		} else {
			logger.info("request uri:{}, origin:{}, access failed", uri, origin);
			return false;
		}
	}
	
	private static final boolean isValid(String origin) {
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
